#!/usr/bin/env python
#-*- coding: UTF-8 -*-
# Python 2.x 
import httplib
import urllib
import urllib2
import json
import time
import ac
appKey = 'ogWUqE30tcnqfLgr'

class TtsHeader:
    def __init__(self, appkey, token):
        self.appkey = appKey
        self.token = token
    def tojson(self, e):
        return {'appkey': e.appkey, 'token': e.token}

class TtsContext:
    def __init__(self, device_id):
        self.device_id = device_id
        #将序列化函数定义到类中
    def tojson(self, e):
        return {'device_id': e.device_id}

class TtsRequest:
    def __init__(self, voice, sample_rate, format, enable_subtitle, text):
        self.voice = voice
        self.sample_rate = sample_rate
        self.format = format
        self.enable_subtitle = enable_subtitle
        self.text = text
    def tojson(self, e):
        return {'volume':100, 'voice': e.voice, 'sample_rate': e.sample_rate, 'format': e.format, 'enable_subtitle': e.enable_subtitle, 'text': e.text, "speech_rate":-200}

class TtsPayload:
    def __init__(self, enable_notify, notify_url, tts_request):
        self.enable_notify = enable_notify
        self.notify_url = notify_url
        self.tts_request = tts_request
    def tojson(self, e):
        return {'enable_notify': e.enable_notify, 'notify_url': e.notify_url, 'tts_request': e.tts_request.tojson(e.tts_request)}

class TtsBody:
    def __init__(self, tts_header, tts_context, tts_payload):
        self.tts_header = tts_header
        self.tts_context = tts_context
        self.tts_payload = tts_payload
    def tojson(self, e):
        return {'header': e.tts_header.tojson(e.tts_header), 'context': e.tts_context.tojson(e.tts_context), 'payload': e.tts_payload.tojson(e.tts_payload)}

def waitLoop4Complete(url, appkey, token, task_id, request_id):
    fullUrl =url+ "?appkey=" + appkey + "&task_id=" + task_id + "&token=" + token + "&request_id=" + request_id
    print "fullUrl=", fullUrl
    host = {"Host":"nls-gateway.cn-shanghai.aliyuncs.com", "Accept":"*/*", "Connection":"keep-alive",'Content-Type': 'application/json'}
    while True:
        req = urllib2.Request(url=fullUrl)
        result = urllib2.urlopen(req).read()
        print "query result = ", result
        jsonData = json.loads(result)
        if jsonData.has_key("error_code") and jsonData["error_code"] == 20000000 and jsonData.has_key("data") and (jsonData["data"]["audio_address"] != None):
            print "Tts Finished! task_id = " + jsonData["data"]["task_id"]
            return jsonData["data"]["audio_address"]
        else:
            print "Tts Running..."
            time.sleep(3)

def requestLongTts4Post(tts_body, appkey, token):
    host = 'nls-gateway.cn-shanghai.aliyuncs.com'
    url = 'https://' + host + '/rest/v1/tts/async'
        # 设置HTTP Headers
    http_headers = {'Content-Type': 'application/json'}
    print('The POST request body content: ' + tts_body)
    conn = httplib.HTTPSConnection(host)
    #conn = httplib.HTTPConnection(host)
    conn.request(method='POST', url=url, body=tts_body, headers=http_headers)
    response = conn.getresponse()
    print('Response status and response reason:')
    print(response.status ,response.reason)
    contentType = response.getheader('Content-Type')
    print(contentType)
    body = response.read()
    if response.status == 200:
        jsonData = json.loads(body)
        print 'The request succeed : ', jsonData
        task_id = jsonData['data']['task_id']
        request_id = jsonData['request_id']
        return waitLoop4Complete(url, appkey, token, task_id, request_id)

def LTTS(role="xiaoyun", text="hello"):
    token = ac.GetToken()
    th = TtsHeader(appKey, token)
    tc = TtsContext("mydevice")
    tr = TtsRequest(role, 16000, "mp3", False, text)
    tp = TtsPayload(False, "", tr)
    tb = TtsBody(th, tc, tp)
    body = json.dumps(tb, default=tb.tojson)
    return requestLongTts4Post(str(body), appKey, token)

if __name__ == "__main__":

    print LTTS(text="今天天气不错")
